const uuidv4 = require('uuid/v4');
const { Model, Schema } = require('../helps/model');

// CREATE TABLE `user` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `username` varchar(50) NOT NULL DEFAULT "" COMMENT '用户名',
//   `password` varchar(255) NOT NULL DEFAULT "" COMMENT '用户密码',
//   `avatar` varchar(255) NOT NULL DEFAULT "" COMMENT '用户头像',
//   `area` varchar(255) NOT NULL DEFAULT "" COMMENT '用户手机国号',
//   `mobile` varchar(255) NOT NULL DEFAULT "" COMMENT '手机号码',
//   `nickname` varchar(255) NOT NULL DEFAULT "" COMMENT '用户昵称',
//   `wechat` varchar(255) NOT NULL DEFAULT "" COMMENT '微信账号',
//   `robot_id` int(11) unsigned NOT NULL DEFAULT 0 COMMENT '机器人id',
//   `type` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '关系类型',
//   `status` tinyint(1) unsigned NOT NULL DEFAULT 1 COMMENT '审核状态：1正常，2禁用',
//   `last_time` datetime COMMENT '最后登入时间',
//   `token` varchar(255) NOT NULL DEFAULT "" COMMENT '登录token',
//   `refresh_token` varchar(255) NOT NULL DEFAULT "" COMMENT '刷新token',
//   `expire_time` datetime COMMENT '最后有效时间',
//   `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   `delete_time` datetime,
//   PRIMARY KEY (`id`),
//   KEY `mobile` (`mobile`) USING BTREE,
//   KEY `robot` (`robot_id`) USING BTREE,
//   KEY `token` (`token`) USING BTREE,
//   KEY `refresh_token` (`refresh_token`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

/**
 * 格式化密码
 * @param password
 * @return {string}
 */
function formatPassword(password) {
  password = `${password}`;
  return `${password.md5()}${password}`.md5();
}

const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'username', 'password', 'avatar', 'area', 'mobile', 'nickname', 'wechat', 'robot_id', 'type', 'status', 'last_time', 'token', 'refresh_token', 'expire_time'],
  default: {
    username: '',
    password: '',
    avatar: '',
    area: '',
    mobile: '',
    nickname: '',
    wechat: '',
    robot_id: 0,
    type: 0,
    status: 1,
    token: '',
    refresh_token: '',
  },
});

/**
 * 判断密码是否一致
 * @param password
 * @return {boolean}
 */
schema.methods.validatePassword = function (password) {
  return this.password === formatPassword(password);
};

/**
 * 刷新token，更改refreshToken
 */
schema.methods.refreshToken = function (seconds) {
  this.token = uuidv4();
  this.refresh_token = uuidv4();
  let now = new Date();
  now.setSeconds(now.getSeconds() + seconds);
  this.expire_time = now;
  return this.save();
};

/**
 * 保存最后登入时间
 */
schema.methods.loginSave = function () {
  this.last_time = new Date();
  return this.save();
};

/**
 * 修改密码
 */
schema.methods.changePassword = function (password) {
  this.password = formatPassword(password);
  return this.save();
};

/**
 * 绑定机器人
 * @param {*} robot_id
 */
schema.methods.bindRobot = function (robot_id) {
  this.robot_id = robot_id;
  return this.save();
};

/**
 * 获取用户信息
 */
schema.methods.info = function () {
  return {
    username: this.username,
    avatar: this.avatar,
    nickname: this.nickname,
    wechat: this.wechat,
    type: this.type,
    token: this.token,
    refresh_token: this.refresh_token,
    expire_time: this.expire_time,
  };
};

/**
 * 更新用户信息
 * @param {*}
 */
schema.methods.put = function ({ username, avatar, nickname, wechat, type }) {
  if (username) this.username = username;
  if (avatar) this.avatar = avatar;
  if (nickname) this.nickname = nickname;
  if (wechat) this.wechat = wechat;
  if (type) this.type = type;
  return this.save();
};

export const model = new Model('user', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add({ username, password, avatar, area, mobile, nickname, wechat }) {
  return model.insert({
    username,
    password: formatPassword(password),
    avatar,
    area,
    mobile,
    nickname,
    wechat,
    status: 1,
    last_time: new Date(),
  });
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, { username, password, avatar, area, mobile, nickname, wechat, status, type }) {
  return model.updateByKey(id, {
    username,
    password: formatPassword(password),
    avatar,
    area,
    mobile,
    nickname,
    wechat,
    type,
    status,
  });
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

/**
 * 根据token查询
 * @param {string} token
 * @returns {*}
 */
export function getByToken(token) {
  return model.one({
    where: [
      ['token', '=', token],
    ],
  });
}

/**
 * 根据mobile查询
 * @param {string} mobile
 * @returns {*}
 */
export function getByMobile(mobile) {
  return model.one({
    where: [
      ['mobile', '=', mobile],
    ],
  });
}
